<template>
  <view class="container">
    <view class="header">
      <view class="back-btn" @click="goBack">
        <text class="iconfont icon-back"></text>
      </view>
      <text class="header-title">注册账号</text>
    </view>
    
    <view class="register-form">
      <!-- 步骤指示器 -->
      <view class="steps">
        <view class="step" :class="{ active: step >= 1, completed: step > 1 }">
          <view class="step-number">1</view>
          <text class="step-text">手机验证</text>
        </view>
        <view class="step-line" :class="{ active: step > 1 }"></view>
        <view class="step" :class="{ active: step >= 2, completed: step > 2 }">
          <view class="step-number">2</view>
          <text class="step-text">设置账号</text>
        </view>
        <view class="step-line" :class="{ active: step > 2 }"></view>
        <view class="step" :class="{ active: step >= 3 }">
          <view class="step-number">3</view>
          <text class="step-text">完成注册</text>
        </view>
      </view>
      
      <!-- 步骤1：手机验证 -->
      <view v-if="step === 1" class="step-content">
        <view class="form-item">
          <text class="label">手机号码</text>
          <view class="input-wrapper">
            <input 
              class="input" 
              type="number" 
              maxlength="11" 
              placeholder="请输入手机号码" 
              v-model="form.phone"
            />
          </view>
        </view>
        
        <view class="form-item">
          <text class="label">验证码</text>
          <view class="input-wrapper code-wrapper">
            <input 
              class="input" 
              type="number" 
              maxlength="6" 
              placeholder="请输入验证码" 
              v-model="form.code"
            />
            <view 
              class="code-btn" 
              :class="{ disabled: codeBtnDisabled }"
              @click="getVerifyCode"
            >{{codeBtnText}}</view>
          </view>
        </view>
        
        <button class="next-btn" @click="validatePhoneStep">下一步</button>
      </view>
      
      <!-- 步骤2：设置账号 -->
      <view v-if="step === 2" class="step-content">
        <view class="form-item">
          <text class="label">用户名</text>
          <view class="input-wrapper">
            <input 
              class="input" 
              type="text" 
              maxlength="20" 
              placeholder="请设置用户名" 
              v-model="form.username"
            />
          </view>
        </view>
        
        <view class="form-item">
          <text class="label">密码</text>
          <view class="input-wrapper">
            <input 
              class="input" 
              :type="showPassword ? 'text' : 'password'" 
              maxlength="20" 
              placeholder="请设置密码" 
              v-model="form.password"
            />
            <text 
              class="iconfont" 
              :class="showPassword ? 'icon-eye-open' : 'icon-eye-close'"
              @click="showPassword = !showPassword"
            ></text>
          </view>
        </view>
        
        <view class="form-item">
          <text class="label">确认密码</text>
          <view class="input-wrapper">
            <input 
              class="input" 
              :type="showConfirmPassword ? 'text' : 'password'" 
              maxlength="20" 
              placeholder="请确认密码" 
              v-model="form.confirmPassword"
            />
            <text 
              class="iconfont" 
              :class="showConfirmPassword ? 'icon-eye-open' : 'icon-eye-close'"
              @click="showConfirmPassword = !showConfirmPassword"
            ></text>
          </view>
        </view>
        
        <button class="next-btn" @click="validateAccountStep">下一步</button>
      </view>
      
      <!-- 步骤3：完成注册 -->
      <view v-if="step === 3" class="step-content">
        <view class="avatar-upload">
          <image class="avatar-img" :src="form.avatar || '/static/images/default-avatar.png'" mode="aspectFill"></image>
          <view class="avatar-btn" @click="chooseAvatar">设置头像</view>
        </view>
        
        <view class="form-item">
          <text class="label">昵称</text>
          <view class="input-wrapper">
            <input 
              class="input" 
              type="text" 
              maxlength="10" 
              placeholder="请输入昵称" 
              v-model="form.nickname"
            />
          </view>
        </view>
        
        <view class="form-item">
          <text class="label">性别</text>
          <view class="gender-options">
            <view 
              class="gender-option" 
              :class="{ active: form.gender === '男' }"
              @click="form.gender = '男'"
            >
              <text class="iconfont icon-male"></text>
              <text>男</text>
            </view>
            <view 
              class="gender-option" 
              :class="{ active: form.gender === '女' }"
              @click="form.gender = '女'"
            >
              <text class="iconfont icon-female"></text>
              <text>女</text>
            </view>
            <view 
              class="gender-option" 
              :class="{ active: form.gender === '其他' }"
              @click="form.gender = '其他'"
            >
              <text class="iconfont icon-other"></text>
              <text>其他</text>
            </view>
          </view>
        </view>
        
        <view class="agreement">
          <view class="checkbox" @click="toggleAgreement">
            <view v-if="form.agreement" class="checkbox-inner"></view>
          </view>
          <text>我已阅读并同意</text>
          <text class="link" @click="navigateTo('/pages/login/agreement')">《用户协议》</text>
          <text>和</text>
          <text class="link" @click="navigateTo('/pages/login/privacy')">《隐私政策》</text>
        </view>
        
        <button class="submit-btn" :disabled="!form.agreement" @click="submitRegistration">完成注册</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      step: 1,
      showPassword: false,
      showConfirmPassword: false,
      codeBtnDisabled: false,
      codeBtnText: '获取验证码',
      countdown: 60,
      form: {
        phone: '',
        code: '',
        username: '',
        password: '',
        confirmPassword: '',
        avatar: '',
        nickname: '',
        gender: '男',
        agreement: false
      }
    }
  },
  methods: {
    // 返回上一页
    goBack() {
      if (this.step > 1) {
        this.step -= 1;
      } else {
        uni.navigateBack();
      }
    },
    
    // 获取验证码
    getVerifyCode() {
      // 如果按钮已禁用，直接返回
      if (this.codeBtnDisabled) {
        return;
      }
      
      // 验证手机号
      if (!this.form.phone) {
        this.showToast('请输入手机号');
        return;
      }
      if (!/^1\d{10}$/.test(this.form.phone)) {
        this.showToast('手机号格式不正确');
        return;
      }
      
      // 禁用按钮并开始倒计时
      this.codeBtnDisabled = true;
      this.countdown = 60;
      this.codeBtnText = `${this.countdown}秒后重新获取`;
      
      // 模拟发送验证码
      this.showToast('验证码已发送，测试验证码：123456', 'none', 3000);
      
      // 开始倒计时
      const timer = setInterval(() => {
        this.countdown -= 1;
        this.codeBtnText = `${this.countdown}秒后重新获取`;
        
        if (this.countdown <= 0) {
          clearInterval(timer);
          this.codeBtnDisabled = false;
          this.codeBtnText = '获取验证码';
        }
      }, 1000);
    },
    
    // 验证第一步：手机验证
    validatePhoneStep() {
      if (!this.form.phone) {
        this.showToast('请输入手机号');
        return;
      }
      if (!/^1\d{10}$/.test(this.form.phone)) {
        this.showToast('手机号格式不正确');
        return;
      }
      if (!this.form.code) {
        this.showToast('请输入验证码');
        return;
      }
      if (this.form.code !== '123456') { // 模拟验证码
        this.showToast('验证码错误');
        return;
      }
      
      // 进入下一步
      this.step = 2;
    },
    
    // 验证第二步：设置账号
    validateAccountStep() {
      if (!this.form.username) {
        this.showToast('请设置用户名');
        return;
      }
      if (this.form.username.length < 4) {
        this.showToast('用户名至少需要4个字符');
        return;
      }
      if (!this.form.password) {
        this.showToast('请设置密码');
        return;
      }
      if (this.form.password.length < 6) {
        this.showToast('密码至少需要6个字符');
        return;
      }
      if (!this.form.confirmPassword) {
        this.showToast('请确认密码');
        return;
      }
      if (this.form.password !== this.form.confirmPassword) {
        this.showToast('两次输入的密码不一致');
        return;
      }
      
      // 进入下一步
      this.step = 3;
    },
    
    // 选择头像
    chooseAvatar() {
      uni.chooseImage({
        count: 1,
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          // 在实际应用中，这里应该上传图片到服务器
          // 这里简单地将临时路径赋值给表单
          this.form.avatar = tempFilePath;
        }
      });
    },
    
    // 切换协议同意状态
    toggleAgreement() {
      this.form.agreement = !this.form.agreement;
    },
    
    // 提交注册
    submitRegistration() {
      if (!this.form.nickname) {
        this.showToast('请输入昵称');
        return;
      }
      if (!this.form.agreement) {
        this.showToast('请同意用户协议和隐私政策');
        return;
      }
      
      // 显示加载
      uni.showLoading({
        title: '注册中...'
      });
      
      // 模拟注册请求
      setTimeout(() => {
        uni.hideLoading();
        
        // 构建用户信息
        const userInfo = {
          avatar: this.form.avatar || '/static/images/default-avatar.png',
          nickname: this.form.nickname,
          gender: this.form.gender,
          location: '未设置',
          bio: '这个人很懒，什么都没有留下',
          phone: this.form.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'),
          email: '',
          joinDate: new Date().toISOString().split('T')[0]
        };
        
        // 保存用户信息
        try {
          uni.setStorageSync('userInfo', JSON.stringify(userInfo));
          uni.setStorageSync('token', 'user_token_' + Date.now());
          
          // 注册成功提示
          uni.showToast({
            title: '注册成功',
            icon: 'success',
            duration: 2000
          });
          
          // 延迟跳转到首页
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/index/index'
            });
          }, 2000);
        } catch (e) {
          console.error('保存用户信息失败:', e);
          this.showToast('注册失败，请重试');
        }
      }, 1500);
    },
    
    // 页面导航
    navigateTo(url) {
      uni.navigateTo({ url });
    },
    
    // 显示提示
    showToast(title, icon = 'none', duration = 2000) {
      uni.showToast({
        title,
        icon,
        duration
      });
    }
  }
}
</script>

<style>
.container {
  padding: 20rpx;
  min-height: 100vh;
  background-color: #f8f8f8;
}

.header {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  margin-bottom: 40rpx;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.register-form {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 30rpx rgba(0,0,0,0.05);
}

.steps {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 60rpx;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.step-number {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  background-color: #eee;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  margin-bottom: 10rpx;
}

.step.active .step-number {
  background-color: #4e8df5;
  color: #fff;
}

.step.completed .step-number {
  background-color: #67c23a;
  color: #fff;
}

.step-text {
  font-size: 24rpx;
  color: #999;
}

.step.active .step-text {
  color: #4e8df5;
}

.step.completed .step-text {
  color: #67c23a;
}

.step-line {
  flex: 1;
  height: 2rpx;
  background-color: #eee;
  margin: 0 10rpx;
  position: relative;
  top: -20rpx;
}

.step-line.active {
  background-color: #67c23a;
}

.step-content {
  padding: 20rpx 0;
}

.form-item {
  margin-bottom: 40rpx;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
}

.input-wrapper {
  position: relative;
  border-bottom: 1rpx solid #eee;
  height: 90rpx;
  display: flex;
  align-items: center;
}

.input {
  flex: 1;
  height: 80rpx;
  font-size: 32rpx;
}

.code-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.code-btn {
  font-size: 28rpx;
  color: #4e8df5;
  padding: 0 20rpx;
  white-space: nowrap;
}

.code-btn.disabled {
  color: #999;
}

.input-wrapper .iconfont {
  color: #999;
  font-size: 36rpx;
}

.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 40rpx 0;
}

.avatar-img {
  width: 160rpx;
  height: 160rpx;
  border-radius: 80rpx;
  margin-bottom: 20rpx;
  border: 2rpx solid #eee;
}

.avatar-btn {
  font-size: 28rpx;
  color: #4e8df5;
  padding: 10rpx 20rpx;
  border: 1rpx solid #4e8df5;
  border-radius: 30rpx;
}

.gender-options {
  display: flex;
  justify-content: space-between;
}

.gender-option {
  flex: 1;
  height: 80rpx;
  border: 1rpx solid #eee;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 10rpx;
  color: #666;
}

.gender-option.active {
  background-color: #e6f3ff;
  border-color: #4e8df5;
  color: #4e8df5;
}

.gender-option .iconfont {
  margin-right: 10rpx;
}

.agreement {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  color: #666;
  margin: 40rpx 0;
}

.checkbox {
  width: 36rpx;
  height: 36rpx;
  border: 1rpx solid #ddd;
  border-radius: 4rpx;
  margin-right: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.checkbox-inner {
  width: 24rpx;
  height: 24rpx;
  background-color: #4e8df5;
  border-radius: 2rpx;
}

.link {
  color: #4e8df5;
  margin: 0 6rpx;
}

.next-btn, .submit-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
  margin-top: 40rpx;
}

.next-btn {
  background: linear-gradient(to right, #4e8df5, #3a78f2);
}

.submit-btn {
  background: linear-gradient(to right, #67c23a, #52b421);
}

.submit-btn[disabled] {
  background: #cccccc;
  color: #fff;
}

.next-btn:active, .submit-btn:active {
  opacity: 0.8;
}
</style> 